<?php
/**
 * ClassName: hospital
 * Description: 中医院管理控制器
 * @Author 周昌
 * @Create 2023/11/8 13:33
 */

namespace app;


use epii\server\Args;
use libs\qrcode\Qrcode;
use libs\Tool;
use model\HospitalModel;
use model\RoomModel;
use service\admin\HospitalService;

class hospital extends base
{
    protected $admin_allow=['index','ajax_data','add_edit','status','del','download'];
    public function init()
    {
        parent::init();
        $this->accessDenied();
    }

    public function index()
    {
        $this->adminUiDisplay();
    }

    public function ajax_data()
    {
        $map = [];
        $name = Args::params('name');
        if ($name) {
            $map[] = ['name', "LIKE", '%' . $name . '%'];
        }
        echo HospitalService::getAjaxData($map);
    }

    public function add_edit()
    {
        $id = Args::params('id');
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            $data = Args::params('r');
            //验证
            $this->validate($data, [
                'name|医院名称' => 'require',
                'phone|医院联系电话' => 'require',
//                'legal_person_name|法人姓名'=>'require|chsAlpha|max:15',
//                'legal_person_phone|法人手机号'=>'require|mobile',
                'address|地址' => 'require|max:255',
                'type|医院类型' => 'require|integer',
                'desc|简介' => '',
                'pid|父id' => 'integer',
                'logo|医院log' => 'require',
                'imgs|轮播图' => 'require',
            ]);
            //logo,imgs 增加oss访问地址
            $data['logo'] = Tool::ossAddDomain($data['logo']);
            $data['imgs'] = Tool::ossAddDomain(explode(',', $data['imgs']));
            $data['imgs'] = implode(',', $data['imgs']);
            if ($id) {
                $res = HospitalService::edit($id, $data);
            } else {
                $data['addtime'] = time();
                $res = HospitalService::add($data);
            }
            $res['code'] ? $this->success($res['msg']) : $this->error($res['msg']);
        }
        $this->_as_info = $id ? HospitalModel::getInfo(['id' => $id]) : [];
        $this->_as_id = $id;
        $this->_as_status = HospitalService::statusSelect();
        $this->_as_hospital_type = HospitalService::hospitalTypeSelect();
        $this->_as_hospital_parent = HospitalService::getSelect(['pid' => 0]);
        $this->_as_addons_static = \epii\server\Tools::get_web_root()."addons_static/";

        $this->adminUiDisplay();
    }

    //修改状态
    public function status()
    {
        $id = Args::params('id/d/1', 'id,不能为空');
        $status = Args::params('status');
        $res = HospitalService::status($id, $status);
        if ($res['code']) {
            $this->success('成功', 'refresh');
        }
        $this->error();
    }

    /**
     * @return array|false|string
     * @throws \think\Exception
     * @throws \think\db\exception\PDOException
     * 删除
     */
    public function del()
    {
        $id = Args::params('id');
        $room_res = RoomModel::getInfo(['hospital_id' => $id]);
        if ($room_res) {
            $this->error('请先删除该医院下房间');
        }
        $res = HospitalService::del($id);
        //todo 判断该事项下是否已经有房间，无则可以删除
        if ($res['code']) {
            $this->success($res['msg'], 'refresh');
        } else {
            $this->error($res['msg']);
        }
    }

    public function modify()
    {
        $id = $this->adminInfo['hospital_id'];
        $this->_as_info = HospitalModel::getInfo(['id' => $id]);
        //排号/签到二维码
        $qrcode_base64 = Qrcode::getQrCode(HospitalService::$qrcode_url . $id);
        $this->_as_qrcode_base64 = 'data:image/png;base64,' . $qrcode_base64;
        $this->adminUiDisplay();
    }
    //修改医院资料
    public function modify_edit()
    {
        $id = Args::params('id/d');
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            $data = Args::params('r');
            //验证
            $this->validate($data, [
//                'name|医院名称'=>'require',
                'phone|医院联系电话' => 'require',
//                'legal_person_name|法人姓名'=>'require|chsAlpha|max:15',
//                'legal_person_phone|法人手机号'=>'require|mobile',
                'address|地址' => 'require|max:255',
//                'type|医院类型'=>'require|integer',
                'desc|简介' => '',
//                'pid|父id'=>'integer',
                'logo|医院log' => 'require',
                'imgs|轮播图' => 'require',
            ]);
            //logo,imgs 增加oss访问地址
            $data['logo'] = Tool::ossAddDomain($data['logo']);
            $data['imgs'] = Tool::ossAddDomain(explode(',', $data['imgs']));
            $data['imgs'] = implode(',', $data['imgs']);
            if ($id) {
                $res = HospitalService::edit($id, $data);
            } else {
                $data['addtime'] = time();
                $res = HospitalService::add($data);
            }
            $res['code'] ? $this->success($res['msg']) : $this->error($res['msg']);
        }
        $this->_as_info = $id ? HospitalModel::getInfo(['id' => $id]) : [];
        $this->_as_id = $id;
        $this->_as_status = HospitalService::statusSelect();
        $this->_as_hospital_type = HospitalService::hospitalTypeSelect();
        $this->_as_hospital_parent = HospitalService::getSelect(['pid' => 0]);
        $this->_as_addons_static = \epii\server\Tools::get_web_root()."addons_static/";

        $this->adminUiDisplay();
    }
    //修改医院logo+轮播图
    public function modify_img()
    {
        $id = Args::params('id/d');
        if ($_SERVER['REQUEST_METHOD'] == "POST") {
            $data = Args::params('r');
            //验证
            $this->validate($data, [
                'logo|医院log' => 'require',
                'imgs|轮播图' => 'require',
            ]);
            //logo,imgs 增加oss访问地址
            $data['logo'] = Tool::ossAddDomain($data['logo']);
            $data['imgs'] = Tool::ossAddDomain(explode(',', $data['imgs']));
            $data['imgs'] = implode(',', $data['imgs']);
            if ($id) {
                $res = HospitalService::edit($id, $data);
            } else {
                $data['addtime'] = time();
                $res = HospitalService::add($data);
            }
            $res['code'] ? $this->success($res['msg']) : $this->error($res['msg']);
        }
        $this->_as_info = $id ? HospitalModel::getInfo(['id' => $id]) : [];
        $this->_as_id = $id;

        $this->adminUiDisplay();
    }

    //下载二维码
    public function download()
    {
        $id = Args::params('id/d');

        $qrcode_base64 = Qrcode::getQrCode(HospitalService::$qrcode_url . $id);
        // 解码 Base64 数据并保存为图片文件
        $imageData = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $qrcode_base64));
        // 创建图像资源
        $image = imagecreatefromstring($imageData);

// 设置图片的宽度和高度
        $width = 500;
        $height = 500;

// 创建缩放后的图像资源
        $newImage = imagecreatetruecolor($width, $height);
        imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, imagesx($image), imagesy($image));

// 设置文件保存路径
        $path = 'qrcode/qrcode.png';
        $mode=0777;
        //判断文件夹存不存在
        if(!file_exists('qrcode')){
            //创建目录并设置权限
            mkdir('qrcode',$mode,true);
        }
        chmod('qrcode',$mode);

// 将图像保存为文件
        imagepng($newImage, $path);

// 输出文件下载
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($path) . '"');
        header('Content-Length: ' . filesize($path));
        readfile($path);

// 删除临时生成的文件
        unlink($path);

// 销毁图像资源
        imagedestroy($image);
        imagedestroy($newImage);

    }
}